<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="85%" @ok="handleSubmit" showFooter destroyOnClose>
    <div style="display: flex">
      <a-row>
        <a-col :sm="13" :md="13" :lg="13" :xl="13">
          <BasicForm @register="registerForm" style="width: 100%">
            <template #payChannel="{ model, field }">
              <a-form-item-rest>
                <div v-for="(item, index) in payChannelSelect" style="margin-top: 5px">
                  <MyRadioGroup v-model:value="item.code" :options="channelOptions" @change="(code) => channelSelectChange(code, index)" />
                  <span> 名称: <a-input v-model:value="item.name" @change="payChannelNameChange" style="width: 75px" size="small" /> </span>
                  <a-button danger size="small" type="link" @click="deletePayChannel(index)">删除</a-button>
                  <a-button v-if="index === payChannelSelect.length - 1 && payChannelSelect.length < 4" size="small" type="link" @click="addPayChannel">
                    新增
                  </a-button>
                </div>
              </a-form-item-rest>
            </template>

            <template #bgColor="{ model, field }">
              <a-form-item-rest>
                <MyRadioGroup v-model:value="model[field]" @change="changeBgColor" :options="colorOptions" />
                <ColorPicker
                  v-if="model[field] === 'custom'"
                  v-model:pureColor="model['customBgColor']"
                  @update:pure-color="changeBgColor"
                  format="hex"
                  :disableAlpha="true"
                />
              </a-form-item-rest>
            </template>
          </BasicForm>
        </a-col>
        <a-col :sm="1" :md="1" :lg="1" :xl="1">
          <Divider :class="`${prefixCls}-qrcode-view-divider`" type="vertical" />
        </a-col>
        <a-col :sm="10" :md="10" :lg="10" :xl="10">
          <div :class="`${prefixCls}-qrcode-view`"  v-if="qrcodeImage">
            <img :src="qrcodeImage" />
          </div>
          <div v-else class="flex justify-center" style="width: 100%">
            <Empty description="暂无预览码牌"></Empty>
          </div>
        </a-col>
      </a-row>
    </div>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, toRaw, computed, unref, useAttrs } from "vue"
  import { BasicForm, useForm, MyRadioGroup } from "/@/components/Form/index"
  import { inputFormSchemas } from "./template.data"
  import {  Empty } from "ant-design-vue"
  import { Divider } from "ant-design-vue"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { saveOrUpdateMchQrcodeTemplate, getMchQrcodeTemplate, getMchQrcodeView } from "/@/api"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { ColorPicker } from "vue3-colorpicker"
  import "vue3-colorpicker/style.css"
  import { useDesign } from "/@/hooks/web/useDesign"
  import { debounce } from "lodash"
  import { UploadBizType } from "/@/enums/uploadEnum"

  const { prefixCls } = useDesign("pay")
  const { createMessage } = useMessage()

  const emit = defineEmits(["success", "register"])
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const isInit = ref(false)
  const record = ref<any>({})
  const qrcodeImage = ref<any>()
  const channelOptions = ref<any[]>([
    { label: "微信", value: "weixin", imgUrl: "" },
    { label: "支付宝", value: "alipay", imgUrl: "" },
  ])
  const colorOptions = ref<any[]>([
    { label: "红色", value: "#FC7851", color: "#FC7851" },
    { label: "绿色", value: "#5DCC7F", color: "#5DCC7F" },
    { label: "青色", value: "#3935EC", color: "#3935EC" },
    { label: "自定义", value: "custom" },
  ])
  const payChannelSelect = ref<any[]>([])

  const [registerForm, { setProps, resetFields, setFieldsValue, validate, getFieldsValue, updateSchema }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    showActionButtonGroup: false,
    wrapperCol: { lg: 20, md: 20 },
  })

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    record.value = data.record
    isInit.value = false
    payChannelSelect.value = record.value.configInfo?.payChannelList || []
    if (payChannelSelect.value.length == 0) {
      addPayChannel()
    }

    setDrawerProps({ confirmLoading: false, loading: true })
    try {
      isUpdate.value = !!data?.isUpdate

      if (unref(isUpdate)) {
        record.value = (await getMchQrcodeTemplate({ id: data.record.id })) || {}
      }

      
      updateSchema([
        {
          field: "styleCode",
          componentProps: ({}) => {
            return {
              options: [
                { label: "模板A", value: "A" },
                { label: "模板B", value: "B" },
              ],
              onChange: (value: any, _) => {
                renderView({ styleCode: value })
              },
            }
          },
        },
        {
          field: "showIdFlag",
          componentProps: ({}) => {
            return {
              options: [
                { label: "是", value: true },
                { label: "否", value: false },
              ],
              onChange: (value: any, _) => {
                renderView()
              },
            }
          },
        },
        {
          field: "showStoreNameFlag",
          componentProps: ({}) => {
            return {
              options: [
                { label: "显示", value: true },
                { label: "隐藏", value: false },
              ],
              onChange: (value: any, _) => {
                renderView()
              },
            }
          },
        },
        {
          field: "qrInnerImgUrl",
          componentProps: ({}) => {
            return {
              fileMax: 1,
              bizType: UploadBizType.GENERAL_IMAGE,
              onChange: (value: any, _) => {
                console.log("value", value)
                renderView()
              },
            }
          },
        },
        {
          field: "logoImgUrl",
          componentProps: ({}) => {
            return {
              fileMax: 1,
              bizType: UploadBizType.GENERAL_IMAGE,
              onChange: (value: any, _) => {
                renderView()
              },
            }
          },
        },
      ])
      await resetFields()
      await setFieldsValue({
        ...record.value,
        ...record.value.configInfo,
      })
      await renderView()

    } finally {
      isInit.value = true
      setDrawerProps({ loading: false })
    }
  })

  const getTitle = computed(() => (!unref(isUpdate) ? "新增码牌模板" : "编辑码牌模板"))

  async function handleSubmit() {
    try {
      let values = await validate()
      setDrawerProps({ confirmLoading: true })
      const data = {
        id: values.id,
        name: values.name,
        styleCode: values.styleCode,
        configInfo: {},
      }
      data.configInfo = await getConfigInfo()

      await saveOrUpdateMchQrcodeTemplate(data, unref(isUpdate))
      closeDrawer()
      createMessage.success(`${getTitle.value}成功`)
      emit("success")
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }

  const getConfigInfo = async () => {
    const formValue = await getFieldsValue()
    const newValue: any = { ...formValue, payChannelList: toRaw(unref(payChannelSelect)) }
    delete newValue.id
    delete newValue.name
    delete newValue.styleCode
    delete newValue.payChannel
    console.log("configInfo", newValue)
    return newValue
  }

  const changeBgColor = async (value) => {
    console.log("bgColor", value)
    renderView()
  }

  const deletePayChannel = (index) => {
    payChannelSelect.value.splice(index, 1)
    renderView()
  }

  const renderView = async (newValue: any = {}) => {
    console.log('renderView', newValue)
    const formValue = await getFieldsValue()
    const configInfo = await getConfigInfo()
    qrcodeImage.value = await getMchQrcodeView({
      styleCode: newValue?.styleCode || formValue.styleCode,
      configInfo,
    })
  }

  const channelSelectChange = async (newCode, index) => {
    console.log("channel", newCode)
    const option = channelOptions.value.find((e) => e.value === newCode)
    const select = payChannelSelect.value[index]
    select.code = option.value
    select.name = option.label
    select.imgUrl = option.imgUrl

    renderView()
  }

  const addPayChannel = () => {
    const option = channelOptions.value[0]
    payChannelSelect.value.push({
      code: option.value,
      name: option.label,
      imgUrl: option.imgUrl,
    })
    if (isInit.value) {
      renderView()
    }
    
  }

  const handlePayChannelNameChannel = () => renderView()
  const payChannelNameChange = debounce(handlePayChannelNameChannel, 1000) //防抖1s
</script>

<style lang="less" scope>
  @prefix-cls: ~"@{namespace}-pay";

  .@{prefix-cls}-qrcode-view-divider {
    height: calc(100vh - 200px);
    margin-right: 10px;
  }

  .@{prefix-cls}-qrcode-view {
    width: 85% !important;
    height: calc(100vh - 150px);
    background-color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;

    img {
      width: 100%;
      height: calc(100vh - 150px);
    }
  }
</style>
